import axios from 'axios';
import store from '../store/index.js';
import {
  local
} from './cache.js'


class HttpRequest {
  constructor() {
    this.baseUrl = process.env.NODE_ENV === 'production' ? 'https://test.yicheyoupin.mygoods.com.cn' : 'https://test.yicheyoupin.mygoods.com.cn';
    this.timeout = 50000;
    this.loadingAPI = {};
  }
  merge(options) {
    return {
      ...options,
      baseURL: this.baseUrl,
      timeout: this.timeout,
    }
  }
  setInterceptor(instance, url) {
    instance.interceptors.request.use(config => {
      if (Object.keys(this.loadingAPI).length === 0) {
        store.commit('SHOW_LOADING')
      }

      this.loadingAPI[url] = url;

      return config;
    })
    instance.interceptors.response.use(res => {


      delete this.loadingAPI[url];

      if (Object.keys(this.loadingAPI).length === 0) {
        store.commit('HIDE_LOADING');
      }
      if (res.data.code && res.data.code != 10000) {
        store.commit('MESSAGE', res.data.message)
      }
      return res.data;
    })
  }
  request(options) {
    if (local.get('token')) {
      options = Object.assign({}, options, {
        headers: {
          authorization: 'Bearer ' + local.get('token')
        }
      })
    }
    const instance = axios.create({});
    const params = this.merge(options);
    this.setInterceptor(instance, params.url);
    return instance(params)
  }
}
export default new HttpRequest;